/**
 * 性能优化
 */
import React, { Component, PureComponent } from 'react'

const Fnc = (props) => {
  console.log(props)
  return <div>123</div>
}

class LessRender extends PureComponent {
  state = {
    count: 0,
    list: ['red', 'blue'],
    obj: { a: 1, b: 2 },
  }

  /**
   *
   * @param {*} nextProps 最新的props
   * @param {*} nextState 最新的state
   */
  // shouldComponentUpdate(nextProps, nextState) {
  //   // console.log(nextProps, nextState)
  //   if (nextState.count !== this.state.count) {
  //     return true
  //   }
  //   return false
  // }

  handlerAdd = () => {
    this.setState({
      count: 10,
    })
  }

  handlerColor = () => {
    // 引用类型：只比较对象的引用地址（指针）是否相同
    // this.state.list.push('orange')
    let newList = ['orange', ...this.state.list]
    // this.state.obj.a = 10000
    let newObj = { ...this.state.obj, a: 10000 }
    this.setState({
      // list: newList,
      obj: newObj,
    })
  }

  render() {
    console.log('LessRender重新渲染了！')
    return (
      <div>
        <h1>减少不必要的重新渲染</h1>
        <p>{this.state.count}</p>
        <p>
          {this.state.obj.a},{this.state.obj.b}
        </p>
        <button onClick={this.handlerAdd}>add</button>
        <hr />
        <ul>
          {this.state.list.map((item) => (
            <li style={{ backgroundColor: item }} key={item}>
              {item}
            </li>
          ))}
        </ul>
        <button onClick={this.handlerColor}>changeColor</button>
        <hr />
        <Fnc key={1} />
      </div>
    )
  }
}

export default LessRender
